<?php
/**
 * @email blog.alipay168.cn
 * @author bs_shop
 * @link http://blog.alipay168.cn
 * @Date: 2022-01-07 21:58:11
 */

namespace app\plugin\controller\bs_db_backup;

use app\plugin\controller\bs_db_backup\com\BsDbBackup;
use app\plugin\controller\bs_db_backup\ext\Backup;
use app\service\Page;

class Index extends BsDbBackup
{
    function index()
    {
        $data = [];
        if (is_dir($this->backup_path)) {
            $dir = scandir($this->backup_path);
            $atime = [];
            foreach ($dir as $file) {
                if ($file == '.' || $file == '..') {
                    continue;
                }
                $atime[] = filectime($this->backup_path . $file);
                $size = filesize($this->backup_path . $file);
                if ($size >= 1024) {
                    $size = round($size / 1024, 2);
                    if ($size >= 1024) {
                        $size = round($size / 1024, 2) . 'MB';
                    } else {
                        $size = $size . 'KB';
                    }
                } else {
                    $size .= 'B';
                }
                $data[] = [
                    'name' => $file,
                    'size' => $size,
                    'time' => fileatime($this->backup_path . $file),
                    'add_time' => date('Y-m-d H:i:s', filectime($this->backup_path . $file)),
                ];
            }

            array_multisort($atime, SORT_DESC, $data);
        }

        $this->assign('data', $data);
        return $this->fetch();
    }

    //新增备份
    public function add_backup()
    {
        if (empty($this->plugin['plugin_data']['save_count']) || $this->plugin['plugin_data']['save_count'] < 0) {
            $this->plugin['plugin_data']['save_count'] = 5;
        }
        $limitCount = min(10, $this->plugin['plugin_data']['save_count']);

        if (is_dir($this->backup_path)) {
            $dir = scandir($this->backup_path);
            $total = 0;
            foreach ($dir as $file) {
                if ($file == '.' || $file == '..') {
                    continue;
                }
                $total++;
            }
            if ($total >= $limitCount) {
                data_return('备份已超过设置上限，请先手动删除旧备份', -1);
            }

        }


        @set_time_limit(1800);
        if (!is_dir($this->backup_path)) {
            @mkdir($this->backup_path, 0775, true);
        }
        if (!is_dir($this->backup_path) || !is_writable($this->backup_path)) {
            data_return('备份目录没有写入权限:' . str_replace(ROOT_PATH, '/', $this->backup_path), -1);
        }
        $conf = config('database');
        //实例化备份类
        $obj = new Backup($conf['hostname'], $conf['username'], $conf['password'], $conf['database'], $this->backup_path, 'uif8');

        //设置名称
        $obj->backupFile = 'bsshop_database_backup' . date('YmdHis') . '.sql';
        //开始备份
        $res = $obj->backupTables();
        data_return();
    }

    //删除备份
    public function del_backup()
    {
        if (empty($this->param['fname'])) {
            data_return('参数不合法', -1);
        }
        if (!file_exists($this->backup_path . trim($this->param['fname']))) {
            data_return('备份不存在', -1);
        }
        $res = @unlink($this->backup_path . trim($this->param['fname']));
        if (!$res) {
            data_return('删除失败', -1);
        }
        data_return('删除成功');
    }

    //下载备份
    public function download_backup()
    {
        @set_time_limit(1800);

        if (empty($this->param['fname'])) {
            data_return('参数不合法', -1);
        }
        if (!file_exists($this->backup_path . trim($this->param['fname']))) {
            data_return('备份不存在', -1);
        }

        $file = @fopen($this->backup_path . trim($this->param['fname']), "rb");
        if (!$file) {
            data_return('读取文件失败', -1);
        }

        /*$extArray = explode('.', $this->backup_path . trim($this->param['fname']));
        //获取扩展名后缀
        $fileExt = $extArray[count($extArray) - 1];*/

        ob_start();
        header('Content-Type:application/zip');
        header('Content-disposition:attachment;filename=' . trim($this->param['fname']));
        $filesize = filesize($this->backup_path . trim($this->param['fname']));
        readfile($this->backup_path . trim($this->param['fname']));
        header('Content-length:' . $filesize);
        ob_end_flush();

        data_return('下载完成', 0);
    }


    //配置的方式，可选
    public static function config()
    {
        $element = [
            [
                'element' => 'input',
                'type' => 'number',
                'default' => '5',
                'label_desc' => '请设置1~10之间',
                'name' => 'save_count',
                'placeholder' => '最多保留的份数',
                'title' => '保留分数',
                'is_required' => 1,
                'message' => '请设置保留的份数，超过则自动删除。',
            ],
            [
                'element' => 'select',
                'title' => '是否压缩',
                'message' => '请选择是否需要压缩',
                'label_desc' => '压缩后会极大地节省磁盘空间和下载资源消耗，建议开启备份压缩（如某数据不压缩大小为20M，压缩后大小为660KB）。',
                'name' => 'is_zip',
                'is_required' => 1,
                'is_multiple' => 0,
                'element_data' => [
                    ['value' => '1', 'name' => '是'],
                    ['value' => '-1', 'name' => '否'],
                ],
            ],

        ];
        return [
            "element" => $element,
        ];
    }
}